# 启动界面主程序
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QTimer
from ui_control import Ui_MainWindow
from soft_keyboard import SoftKeyboard
import utils
import signal

FOCUSIN  = 10
FOCUSOUT = 11
class ControlWindow(QMainWindow):
	def __init__(self):
		super().__init__()
		signal.signal(signal.SIGINT, self.handle_sigint)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.hc = utils.HardwareController
		utils.load_config()
		# 启动时检查串口连接情况
		serial_status = utils.check_serial_port()
		self.ui.label.setText(serial_status)

		# self.ui.plainTextEdit.installEventFilter(self)
		for obj in [
			self.ui.plainTextEdit,
			self.ui.plainTextEdit_10,
			self.ui.plainTextEdit_9,
			self.ui.plainTextEdit_2,
			self.ui.plainTextEdit_3,
			self.ui.plainTextEdit_4,
			self.ui.plainTextEdit_5,
			self.ui.plainTextEdit_6,
			self.ui.plainTextEdit_7,
			 ]:
			obj.installEventFilter(self)
		self.soft_keyboard = SoftKeyboard()

		# 定时器设置
		self.timer = QTimer(self)
		self.timer.timeout.connect(self.query_temperatures)
		# self.timer.start(1000)  # 每秒钟触发一次

		# 超净台风机（低速）
		self.ui.radioButton_7.clicked.connect(lambda: self.hc.set_fan2(1 if self.ui.radioButton_7.isChecked() else 0))
		# 超净台风机（高速）
		self.ui.radioButton_6.clicked.connect(lambda: self.hc.set_fan2(1 if self.ui.radioButton_6.isChecked() else 0))
		# 紫外灯
		self.ui.radioButton.clicked.connect(lambda: self.hc.set_uv_lamp(1 if self.ui.radioButton.isChecked() else 0))
		# 日光灯
		self.ui.radioButton_2.clicked.connect(lambda: self.hc.set_lighting(1 if self.ui.radioButton_2.isChecked() else 0))
		# 声光报警
		self.ui.radioButton_5.clicked.connect(lambda: self.hc.set_alarm(1 if self.ui.radioButton_5.isChecked() else 0))

		# 反应釜加热器
		self.ui.radioButton_8.clicked.connect(lambda: self.hc.set_reactor_heater(1 if self.ui.radioButton_8.isChecked() else 0))
		# 管道加热器
		self.ui.radioButton_9.clicked.connect(lambda: self.hc.set_duct_heater(1 if self.ui.radioButton_9.isChecked() else 0))
		# 半导体制冷片
		self.ui.radioButton_10.clicked.connect(lambda: self.hc.set_refrigeration(1 if self.ui.radioButton_10.isChecked() else 0))
		# 半导体制冷片风扇
		self.ui.radioButton_13.clicked.connect(lambda: self.hc.set_fan1(255 if self.ui.radioButton_13.isChecked() else 0))

		# 进气电磁阀
		self.ui.radioButton_11.clicked.connect(lambda: self.hc.set_valve1(1 if self.ui.radioButton_11.isChecked() else 0))

		# 增压泵
		self.ui.radioButton_15.clicked.connect(lambda: self.hc.set_pump_state(1 if self.ui.radioButton_15.isChecked() else 0))

		# 磁力搅拌器转速设置
		self.ui.pushButton_18.clicked.connect(self.ui_set_motor_speed)

		# 泄气阀开度设置
		self.ui.pushButton_20.clicked.connect(self.ui_set_valve2)
		self.ui.pushButton_12.clicked.connect(self.ui_get_pump_pres)
		self.ui.pushButton_17.clicked.connect(self.ui_get_traffic)

		# 控制台发送命令
		self.ui.pushButton.clicked.connect(self.send_console_command)

	def send_console_command(self):
		text = self.ui.plainTextEdit.toPlainText().strip()
		if not text:
			return
		import subprocess
		try:
			result = subprocess.run(text, shell=True, capture_output=True, text=True)
			output = result.stdout + result.stderr
		except Exception as e:
			output = str(e)
		self.ui.textBrowser.append(f"$ {text}\n{output}")
		self.ui.plainTextEdit.clear()
	def eventFilter(self, obj, event):
		if obj in [
			self.ui.plainTextEdit,
			self.ui.plainTextEdit_10,
			self.ui.plainTextEdit_9,
			self.ui.plainTextEdit_2,
			self.ui.plainTextEdit_3,
			self.ui.plainTextEdit_4,
			self.ui.plainTextEdit_5,
			self.ui.plainTextEdit_6,
			self.ui.plainTextEdit_7,
			 ]:
			if event.type() == FOCUSIN:
				self.soft_keyboard.set_target(obj)
				self.soft_keyboard.show_keyboard()
		return super().eventFilter(obj, event)
	
	def ui_set_motor_speed(self):
		try:
			# 获取磁力搅拌器转速中的文本并转换为整数
			value_text = self.ui.plainTextEdit_10.toPlainText().strip()
			value = int(value_text)
			
			if -1000 <= value <= 1000:
				result = self.hc.set_motor_speed(value)

		except ValueError:
			print("请输入有效的数字")

	def ui_set_valve2(self):
		try:
			# 获取泄气阀开度中的文本并转换为整数
			value_text = self.ui.plainTextEdit_9.toPlainText().strip()
			value = int(value_text)
			
			if 0 <= value <= 4095:
				result = self.hc.set_valve2(value)

		except ValueError:
			print("请输入有效的数字")
	
	def ui_get_traffic(self):
		traffic = self.hc.get_traffic()
		self.ui.lcdNumber_7.display(traffic)
		...
	def ui_get_pump_pres(self):
		ppres = self.hc.get_pump_pres()
		self.ui.lcdNumber_6.display(ppres)
		...

	def query_temperatures(self):
		try:
			temp_duct = self.hc.get_temp_duct()
			reactor_temp = self.hc.get_reactor_temp()
			pump_temp = self.hc.get_temp_pump()
			# traffic = self.hc.get_traffic()
			# ppres = self.hc.get_pump_pres()

			# 更新LCD显示
			self.ui.lcdNumber_3.display(temp_duct)
			self.ui.lcdNumber.display(reactor_temp)
			self.ui.lcdNumber_4.display(pump_temp)
			# self.ui.lcdNumber_7.display(traffic)
			# self.ui.lcdNumber_6.display(ppres)
		except Exception as e:
			print(f"Error querying temperatures: {e}")
	def handle_sigint(self, signum, frame):
		print("SIGINT received, stopping timer...")
		self.timer.stop()
		QApplication.quit()

if __name__ == "__main__":
	app = QApplication(sys.argv)
	window = ControlWindow()
	window.show()
	sys.exit(app.exec())
